﻿namespace WcfDataSet.OMR
{
    using System;
    using System.Data;
    using System.IO;

    // BinaryFormatter
    using System.Runtime.Serialization.Formatters.Binary;

    public static class SystemDataExtensions
    {
        public static CustomDataTable GenerateCustom(this DataTable dataTable)
        {
            if (dataTable == null)
                throw new ArgumentException("dataTable");

            var returnValue = new CustomDataTable(dataTable.Columns.Count, dataTable.Rows.Count);

            returnValue.Name = dataTable.TableName;

            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                var c = new CustomColumnInfo();
                c.Name = dataTable.Columns[i].ColumnName;
                c.DataTypeOfString = dataTable.Columns[i].DataType.FullName;

                returnValue.Columns[i] = c;
            } // for

            for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
            {
                var row = new CustomDataRow(returnValue.Columns.Length);
                
                for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++)
                {
                    var cd = new CustomColumnData();
                    cd.Data = dataTable.Rows[rowIndex][columnIndex].SerializeToByteArray();

                    row.ColumnData[columnIndex] = cd;
                } // for

                returnValue.Rows[rowIndex] = row;
            } // for

            return returnValue;
        } // GenerateCustom

        public static CustomDataSet GenerateCustom(this DataSet dataSet)
        {
            if (dataSet == null)
                throw new ArgumentException("dataSet");

            var returnValue = new CustomDataSet(dataSet.Tables.Count);

            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                returnValue.Tables[i] = dataSet.Tables[i].GenerateCustom();
            }

            return returnValue;
        } // GenerateCustom

        private static byte[] SerializeToByteArray(this object obj)
        {
            if (obj == null)
                return null;

            var binaryFormatter = new BinaryFormatter();

            using (var memoryStream = new MemoryStream())
            {
                binaryFormatter.Serialize(memoryStream, obj);

                return memoryStream.ToArray();
            }

        } // SerializeToByteArray

    }
}